﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Lib.Common;
using SDT.Model;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 25/06/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class QuestionCategoryController : Controller
    {
        SDTDataContext eDataContext = new SDTDataContext();
        //
        // GET: /QuestionCategory/

        public ActionResult Index(int? page)
        {
            try
            {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("questionCategory.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("questionCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("questionCategory.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("questionCategory.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("questionCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);

                    var categories = eDataContext.QuestionCategories
                        .Where(c => CurrentPubStatus.HasValue ? c.ActiveYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new QuestionCategoryViewModels
                    {
                        Categories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /QuestionCategory/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                    QuestionCategory proCat = eDataContext.QuestionCategories.Where(c => c.ID == id).SingleOrDefault();

                    //List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                    //                                .Where(c => c.ID != proCat.ID)
                    //                                .Select(c => new TreeNodeItem()
                    //                                {
                    //                                    Value = c.ID,
                    //                                    Text = c.Name,
                    //                                    ParentID = c.ParentID
                    //                                }).ToList();
                    //TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, proCat.ParentID);

                    return View(new QuestionCategoryInputModels
                    {
                        //ListParentCategories = categories,
                        Category = proCat,
                        ID = id
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;

                return View(new QuestionCategoryInputModels
                {
                    ID = id
                });
            }
        }

        //
        // GET: /QuestionCategory/Create

        public ActionResult Create()
        {
            try
            {
                    //List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                    //                                .Select(c => new TreeNodeItem()
                    //                                {
                    //                                    Value = c.ID,
                    //                                    Text = c.Name,
                    //                                    ParentID = c.ParentID
                    //                                }).ToList();
                    //TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new QuestionCategoryInputModels
                    {
                        //ListParentCategories = categories
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /QuestionCategory/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                    // TODO: Add insert logic here
                    QuestionCategory docCat = new QuestionCategory();
                    UpdateModel(docCat);
                    docCat.AddBy = UserManager.GetUserId();
                    eDataContext.QuestionCategories.InsertOnSubmit(docCat);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /QuestionCategory/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                    QuestionCategory proCat = eDataContext.QuestionCategories.Where(c => c.ID == id).SingleOrDefault();

                    //List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                    //                                .Where(c => c.ID != proCat.ID)
                    //                                .Select(c => new TreeNodeItem()
                    //                                {
                    //                                    Value = c.ID,
                    //                                    Text = c.Name,
                    //                                    ParentID = c.ParentID
                    //                                }).ToList();
                    //TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, proCat.ParentID);

                    return View(new QuestionCategoryInputModels
                    {
                        //ListParentCategories = categories,
                        Category = proCat
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /QuestionCategory/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                    QuestionCategory proCat = eDataContext.QuestionCategories.Where(c => c.ID == id).SingleOrDefault();
                    UpdateModel(proCat);
                    proCat.ModifyBy = UserManager.GetUserId();
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }


        //
        // GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    int nItem = eDataContext.QuestionCategories.Where(d => d.ParentID.HasValue && d.ParentID.Value == id).Count();
                    if (nItem > 0)
                        throw new Exception("Chuyên mục bạn xoá là chuyên mục cha. Bạn phải xoá chuyên mục con rồi mới xoá được.");

                    QuestionCategory formDoc = eDataContext.QuestionCategories.Where(f => f.ID == id).FirstOrDefault();

                    return View(formDoc);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    QuestionCategory formDoc = eDataContext.QuestionCategories.Where(f => f.ID == id).FirstOrDefault();
                    if (formDoc != null)
                    {
                        eDataContext.QuestionCategories.DeleteOnSubmit(formDoc);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
